package com.vf.admin.platform.controller;

import com.vf.admin.common.BaseController;
import com.vf.admin.common.Constants;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.platform.entity.Organ;
import com.vf.admin.platform.entity.User;
import com.vf.admin.platform.service.OrganService;
import com.vf.admin.platform.service.UserService;
import com.vf.admin.utils.StringEx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 平台组织机构
 */
@Controller
@RequestMapping(value="/organ")
public class OrganController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private OrganService organService;
    @Autowired
    private UserService userService;
    @Resource
    RedisUtil redisUtil;

    /**
     * 获取所有下级的组织结构
     * @return
     */
    @RequestMapping("/left")
    @ResponseBody
    public Result findList(Integer defaultId){
        System.out.println("defaultId:"+defaultId);
        List<Organ> list = new ArrayList<Organ>();
        try {
//            String jessionid = request.getSession().getId();
//            boolean jessionExists = redisUtil.hasKey(jessionid);
//            if(!jessionExists){
//
//            }
//            User user = (User)redisUtil.get(jessionid);

            User user = (User)request.getSession(false).getAttribute(Constants.access_token);
            List<Organ>  orgListbf = organService.getOrgAllList();
            orgListbf = getOrgAll(orgListbf,new ArrayList(),user.getOrgid());
            list= new ArrayList<Organ>();
            for(Organ org : orgListbf){
                if(!list.contains(org)){
                    list.add(org);
                }
            }

            //获取最订单的菜单
            int maxId = 0;
            System.out.println("defaultId:"+defaultId);
            if(defaultId!=null && defaultId>0){
                maxId = defaultId;
            }else{
                if(list!=null && list.size()>0){
                    list = list.stream().sorted(Comparator.comparing(Organ::getSorts).reversed()).collect(Collectors.toList());
                    Optional<Organ > organOption = list.stream().min(Comparator.comparingInt(Organ ::getId));
                    Organ organ = organOption.get();
                    maxId = organ.getId();
                }
            }
            Map<String,Object> retMap = new HashMap<String,Object>();
            retMap.put("defaultId",maxId);
            retMap.put("list",list);
            return this.sucessJSON(retMap,"返回成功!");
        } catch (Exception e) {
            logger.error("查询组织机构列表异常", e);
            return this.errorJSON("操作异常，请联系管理员");
        }
    }

    /**
     * 获取单个组织机构详情
     * @param id 组织的主键
     * @return
     */
    @RequestMapping("/detail")
    public String detail(Integer id){
        try{
            if(StringEx.isNullOrLing(id)){
                return this.error("组织机构编号不能为空");
            }
            Organ organ = organService.get(id);
            if(organ == null){
                return this.error("组织机构不存在");
            }
            if(organ.getPid()!=null && organ.getPid().intValue() == -1){
                organ.setPname("当前是最高等级");
            }
            Map<Integer,String> shiFouStateMap = Constants.getShiFouStateMap();

            request.setAttribute("shiFouStateMap",shiFouStateMap);
            request.setAttribute("organ",organ);
            return this.sucess("/web/platform/organ/edit");
        }catch(Exception e){
            logger.error("查询组织机构详情异常", e);
            return this.error("查询组织机构详情异常");
        }
    }

    /**
     * 保存更新组织机构
     *  organ
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public Result saveOrUpdate(Organ organ){
        try{
            if(StringEx.isNull(organ.getTitle())){
                return this.errorJSON("组织机构名称不能为空!");
            }

            if(organ.getId()==null || organ.getId()<=0){
                if(StringEx.isNullOrLing(organ.getPid())){
                    return this.errorJSON("没有父组织机构，不合法!");
                }
                organ.setStates(organ.getStates() == null ? Constants.shiFou_STATE_FOU : organ.getStates());
                organService.saveOrUpdate(organ);
            }else{
                Organ organBf = organService.get(organ.getId());
                if(organBf == null){
                    return this.errorJSON("组织机构不存在!");
                }
                organBf.setTitle(organ.getTitle());//组织结构名称
                if(organBf.getPid()!=null && organBf.getPid().intValue() == -1){
                    //最高组织机构不能修改启用状态
                }else{
                    organBf.setStates(organ.getStates() == null ? Constants.shiFou_STATE_FOU : organ.getStates());
                }
                organBf.setComments(organ.getComments());//备注
                organBf.setSorts(organ.getSorts());//排序值
                organService.saveOrUpdate(organBf);
                return this.sucessJSON("操作成功！");
            }
            return this.sucess();
        }catch(Exception e){
            logger.error("保存更新组织机构异常", e);
            return this.errorJSON("保存更新组织机构异常!");
        }
    }


    /**
     * 删除组织机构
     * @param id   结构id
     * @return
     */
    @RequestMapping("/del")
    @ResponseBody
    public Result del(Integer id){
        try{
            if(id == null || id<=0){
                return this.errorJSON("组织机构编号不能为空!");
            }
            Organ organ = organService.get(id);
            if(organ==null || organ.getId()==null || organ.getId()<=0){
                return this.errorJSON("组织机构编号不能为空!");
            }

            if(organ.getPid()!=null && organ.getPid().intValue() == -1){
                //最高组织机构无法删除
                return this.errorJSON("最高组织机构不允许删除!");
            }else{
                Map<String,Object> paraMap = new HashMap<String,Object>();
                paraMap.put("orgid",organ.getId());
                List<User> userList = userService.findList(paraMap,null);
                if(userList!=null && userList.size()>0){
                    return this.errorJSON("该组织机构存在用户，无法删除!");
                }
                paraMap.clear();
                paraMap.put("pid",organ.getId());
                List<Organ> organList = organService.findList(paraMap,null);
                if(organList!=null && organList.size()>0){
                    return this.errorJSON("存在下级组织机构，无法删除!");
                }

                organService.del(organ.getId());
            }
            return this.sucessJSON("操作成功！");
        }catch (Exception e){
            logger.error("删除组织机构异常", e);
            return this.errorJSON("删除组织机构异常!");
        }
    }

    /**
     * 递归当前登陆用户的组织机构id下的所有组织机构id
     */
    private List<Organ> getOrgAll(List<Organ> orgList,List<Organ> organlistbf,int orgid){
        for(Iterator<Organ> it = orgList.iterator(); it.hasNext();){
            Organ organ = it.next();
            int orgpidbf = organ.getPid();
            int orgidbf = organ.getId();
            if(orgidbf==0){
                organlistbf.add(organ);
            }else if(orgidbf==orgid){
                organlistbf.add(organ);
            }else if(orgpidbf==orgid){
                organlistbf.add(organ);
                organlistbf = getOrgAll(orgList,organlistbf,orgidbf);
            }
        }
        return organlistbf;
    }

}
